#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    int pipe_id[2]={0};
    //创建管道文件资源
    int ret=pipe(pipe_id);
    if(ret<0)
    {
        perror("pipe");
        exit(1);
    }
    printf("pipe_id[0]:%d pipe_id[1]:%d\n",pipe_id[0],pipe_id[1]);
    //创建子进程，共享管道资源
    pid_t id=fork();
    if(id==0)
    {
        close(pipe_id[1]);
        //进行读取管道信息
        while(1)
        {
            char buffer[128]={0};
            ssize_t s=read(pipe_id[0],buffer,sizeof(buffer)-1);//给结束符留一个位置
            if(s>0)
            {
                buffer[s]=0;//设置结束符
                printf("msg from father:%s",buffer);
            }
            else if(s==0)
            {
                printf("写进程端口关闭...\n");
                break;
            }
            else 
                break;
        }
        close(pipe_id[0]);
        exit(0);
    }
    else if(id>0)
    {
        close(pipe_id[0]);
        const char* msg="Hello child, I am your father!\n";
        int cnt=0;
        while(1)
        {
            cnt++;
            printf("father write:%d\n",cnt);
            write(pipe_id[1],msg,strlen(msg));//结束符不用写入，结束符是C语言的规则不是系统的规则
            sleep(1);
            if(cnt==10)
                break;
        }
        close(pipe_id[1]);
    }
    else 
    {
        perror("fork");
        exit(2);
    }
    //父进程等待
    int status=0;
    if(waitpid(id,&status,0)>0&&WIFEXITED(status))//等待成功并退出正常
    {
        printf("wait success! exit code:%d\n",WEXITSTATUS(status));
    }
    else  
    {
        printf("exit sign:%d\n",status&0x7F);
    }
    return 0;
}

